/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aptech.servlet;

import aptech.container.Constants;
import aptech.data.TypeOfUserBO;
import aptech.data.UserBO;
import aptech.entities.Users;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import aptech.sendmail.GMailUtil;

/**
 *
 * @author home
 */
@WebServlet(name = "RegisterAccountServlet", urlPatterns = {"/RegisterAccountServlet"})
public class RegisterAccountServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String type = request.getParameter(Constants.TYPE);
            String action = request.getParameter(Constants.ACTION);
            //register
            if (type == null) {
                if (action.equals(Constants.ACTION_ADD)) {
                    String username = request.getParameter(Constants.USER_NAME);
                    String password = request.getParameter(Constants.PASSWORD);
                    String email = request.getParameter(Constants.EMAIL);
                    if (username == null || password == null || email == null) {
                        out.println("<result>error</result>");
                    } else {
                        Users user = new Users();
                        user.setUsernameLogin(username);
                        user.setPasswordLogin(password);
                        user.setEmailLogin(email);
                        String keycode = getKeyCode();
                        user.setCodeActive(keycode);
                        user.setStatusActive("False");//default false, it means account doesn't active
                        user.setTypeOfUser(new TypeOfUserBO().getById(2, true));//2: USER, 1: ADMIN
                        boolean kq = new UserBO().addNew(user);
                        if (kq) {
                            //send mail
                            GMailUtil.send(email,"Congratulation" ,contentMail(keycode));
                            //edit active code
                            out.println("<result>success</result>");
                        }
                    }
                }
                if (action.equals(Constants.ACTION_EDIT)) {
                    //do sth
                    String userid = request.getParameter(Constants.USER_ID);
                    Users user = new UserBO().getById(Integer.parseInt(userid), true);
                    if(user!=null){
                        String password = request.getParameter(Constants.PASSWORD);
                        String address = request.getParameter(Constants.ADDRESS);
                        String gender = request.getParameter(Constants.GENDER);
                        String dateofbirth = request.getParameter(Constants.DATEOFBIRTH);
                        String avartar = request.getParameter(Constants.AVARTAR);
                        if(password==null){
                            password="password";
                        }
                        if(address==null){
                            address="address";
                        }
                        if(gender==null){
                            gender="Male";
                        }
                        if(dateofbirth==null){
                            dateofbirth="2011/12/30";
                        }
                        if(avartar==null){
                            avartar="avartar.jsp";
                        }
                        user.setPasswordLogin(password);
                        user.setAddress(address);
                        user.setGender(gender);
                        user.setDateOfBirth(dateofbirth);
                        user.setAvatarPicture(avartar);
                        boolean kq = new UserBO().update(user);
                        if(kq){
                            out.println("<result>success</result>");
                        }
                    }
                }
                if (action.equals(Constants.ACTION_DELETE)) {
                    //do sth
                }
            } else {
                //check username exist
                if (type.equals(Constants.USER_NAME) && action.equals(Constants.ACTION_CHECK)) {
                    String username = request.getParameter(Constants.USER_NAME);
                    boolean kq = new UserBO().checkUsernameExist(username);
                    if (kq) {
                        out.println("<result>exist</result>");
                    } else {
                        out.println("<result>You can use this account!</result>");
                    }
                }
                //check email exist
                if (type.equals(Constants.EMAIL) && action.equals(Constants.ACTION_CHECK)) {
                    String email = request.getParameter(Constants.EMAIL);
                    boolean kq = new UserBO().checkEmailExist(email);
                    if (kq) {
                        out.println("<result>exist</result>");
                    } else {
                        out.println("<result>You can use this email!</result>");
                    }
                }
            }

        } catch (Exception ex) {
            out.println("<result>error</result>");
            ex.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    private  String getKeyCode() {
        double randomNumber;
        double randomNumberSetup;
        char randomCharacter;
        StringBuilder code = new StringBuilder();
        int r ;
        for (int i = 0; i < 20; i++) {
            if (i % 2 == 0) {
                randomNumber = Math.random();
                randomNumberSetup = (randomNumber * 26 + 'a');
                randomCharacter = (char) randomNumberSetup;
                code.append(new String(randomCharacter+"").toUpperCase());

            }else{
                r = new Random().nextInt(9999);
                code.append(r);
            }

        }
        return code.toString();
    }

    private String contentMail(String codeactive){
        StringBuilder content = new StringBuilder();
        content.append("Hi. Your registration has been successful.");
        content.append("<br/><br/> Please, You click below link to register complete");
        content.append("<br/><br/>");
        content.append("<a href='localhost:8080/NLPP_SEM4/LoginServlet?action=activecode&");
        content.append(Constants.CODE_ACTIVE);
        content.append("=");
        content.append(codeactive);
        content.append("'>localhost:8080/NLPP_SEM4/LoginServlet?action=activecode&");
        content.append(Constants.CODE_ACTIVE);
        content.append("=");
        content.append(codeactive);
        content.append("</a>");
        content.append("<br/><br/> Thank you.");
        return content.toString();
    }
    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>


}
